package com.scqzy.shengchunqiang.sword2offer.day06;

import com.scqzy.shengchunqiang.structure.TreeNode;

import java.util.*;

/**
 * @Description: 剑指 Offer 32 - I. 从上到下打印二叉树
 * @Author 盛春强
 * @Date 2021/8/13 22:37
 */
public class LevelOrder {
    public int[] levelOrder(TreeNode root) {
        if (Objects.isNull(root)) {
            return new int[0];
        }
        Deque<TreeNode> deque = new ArrayDeque<>();
        List<Integer> list = new ArrayList<>();
        deque.offer(root);
        list.add(root.val);
        while (!deque.isEmpty()) {
            TreeNode poll = deque.poll();
            if (Objects.nonNull(poll.left)) {
                list.add(poll.left.val);
                deque.offer(poll.left);
            }
            if (Objects.nonNull(poll.right)) {
                list.add(poll.right.val);
                deque.offer(poll.right);
            }
        }
        return list.stream().mapToInt(Integer::intValue).toArray();
    }
}
